package com.kevin.Code.Tree;

import java.util.*;

/**
 * @author Vinlee Xiao
 * @Classname BinaryTreeLevelOrderTraversali
 * @Description Leetcode 107. 二叉树的层序遍历 II 中等难度
 * @Date 2021/12/15 10:51
 * @Version 1.0
 */
public class BinaryTreeLevelOrderTraversali {

    List<List<Integer>> result = new ArrayList<>();

    /**
     * 广度优先遍历 自己思路
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        if (root == null) {
            return result;
        }

        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);

        while (!deque.isEmpty()) {

            int size = deque.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {

                TreeNode node = deque.pollFirst();
                list.add(node.val);

                if (node.left != null) {
                    deque.addLast(node.left);
                }

                if (node.right != null) {
                    deque.addLast(node.right);
                }
            }
            result.add(list);

        }

        Collections.reverse(result);

        return result;
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(9);
        TreeNode node3 = new TreeNode(20);
        TreeNode node4 = new TreeNode(15);
        TreeNode node5 = new TreeNode(7);

        node1.left = node2;
        node1.right = node3;
        node3.left = node4;
        node3.right = node5;

        BinaryTreeLevelOrderTraversali b = new BinaryTreeLevelOrderTraversali();
        List<List<Integer>> lists = b.levelOrderBottom(node1);

        for (List<Integer> list : lists) {
            for (Integer e : list) {
                System.out.print(e + " ");
            }
            System.out.println();
        }
    }
}
